package com.xyz.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
   //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getshiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean= new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro内置过滤器,拦截
        /*
        * anon : 无序认证就可以访问
        * authc : 必须认证了才能访问
        * user : 必须用拥有记住我才能用
        * perms : 拥有对某个资源的授权才能访问
        * role : 拥有某个角色才能访问
        * */
        Map<String,String> filtMap=new LinkedHashMap<>();
        //授权,权限为13141955194时才能访问
        filtMap.put("/user/add","perms[13141955194]");
        filtMap.put("/user/update","perms[15766205394]");
        //设置未授权请求
        bean.setUnauthorizedUrl("/noauth");

        //拦截
        //filtMap.put("/user/add","authc");
        //filtMap.put("/user/updata","authc");
        //注意：此处  filterMap.put("/user/*",“authc”); 该行代码必须放在授权的代码下，否则授权的拦截无效！
        filtMap.put("/user/*","authc");

        bean.setFilterChainDefinitionMap(filtMap);

        //设置登录请求
        bean.setLoginUrl("/tologin");

        return bean;
    }

   //DafaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager =new DefaultWebSecurityManager();
        //关联UserRealm
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    //创建 realm 对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合ShiroDialect :用来整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
